#ecoding: utf-8 -*-

"""
数据库工具类
使用方法
#config.py文件

import MySQLdb

config = {'creator':MySQLdb, 'maxusage':0, 'db':
              {'host':'localhost', 'user':'root', 'passwd':'root', 'db':'test', 'charset':'utf8'}
          }

#test.py代码文件
from database import connectionFactory
from database import DbUtils
from database import transactions

#connection是线程安全的，可以多线程共享
@transactions
def func():
   connection = connectionFactory.getConnection() 
   cur = connection.cursor()
   cur.execute('insert into test(title, content) values(%s, %s)', ['abc', 'hello'])

   sql = "select * from mytest"
   cursor = connection.cursor()
   cursor.execute(sql)
   l = DBUtils.cursor2obj(cursor)
   for o in l:
     print o.title
     print o.name
"""
from DBUtils.PersistentDB import PersistentDB
from pynixweb.config import config
import uuid

config = config['db']

class _ConnectionFactory:
    """连接工厂"""
    def __init__(self, creator, maxusage=0, *kw, **args):
        self.persist = PersistentDB(creator, maxusage, *kw, **args)

    def getConnection(self):
        connection = self.persist.connection()
        return connection

ConnectionFactory = _ConnectionFactory(config['creator'], config['maxusage'], **config['db']);

class Page:
    """分页对象"""
    pageSize = 0 
    totalSize = 0
    data = []
    def __init__ (self, start, totalSize, pageSize):
        self.pageSize = pageSize
        self.totalSize = totalSize
        self.start = start
    
    def totalPageCount(self):
        if (self.totalSize % self.pageSize == 0):
            return self.totalSize / self.pageSize
        else:
            return self.totalSize / self.pageSize + 1
    
    def currentPageNo(self):
        return self.start/self.pageSize+1
        
    @staticmethod    
    def startOfPage(pageNo, pageSize=10):
        return (pageNo - 1) * pageSize
    
def transactions(func):
    """事务外观"""
    def transactionFun(*args, **kargs):
        connection = ConnectionFactory.getConnection()
        result = None
        try:
            result = func(*args, **kargs)
            connection.commit()
        except Exception, e:
            raise e
            connection.rollback()
        finally:
            connection.close()
        return result
    return transactionFun

class Query:
    @staticmethod
    def executeQuery(sql=None, params=None):
        connection = ConnectionFactory.getConnection()
        cur = None
        cur = connection.cursor()
        if(sql != None):
            if(params == None):
                cur.execute(sql)
            else:
                cur.execute(sql, params)
        return cur

def getuuid():
    return uuid.uuid1()
